package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.GrowthValRecord;
import com.zuipin.entity.Member;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.MemberLevel;
import com.zuipin.entity.MemberRecord;
import com.zuipin.entity.ThirdAccount;
import com.zuipin.entity.shoppingCart.ShowType;
import com.zuipin.enums.GrowthValType;
import com.zuipin.enums.MemberRecordType;
import com.zuipin.enums.MemberStatus;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.MemberAccountMapper;
import com.zuipin.service.IGrowthValRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IMemberRecordService;
import com.zuipin.service.IMemberService;
import com.zuipin.service.IPayOrderService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.IThirdAccountService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Encryption;
import com.zuipin.util.Pagination;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.MemberAccountVo;
import com.zuipin.vo.MemberInfoVo;

/**
 * @ClassName: MemberAccountServiceImpl
 * @author wuyicheng
 * @time 2017年3月27日下午4:02:26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberAccountServiceImpl implements IMemberAccountService {
	
	@Resource
	private MemberAccountMapper		memberAccountMapper;
	@Resource
	private IMemberService			memberService;
	@Resource
	private IThirdAccountService	thirdAccountService;
	@Resource
	private IPayOrderService		payOrderService;
	@Resource
	private IMemberLevelService		memberLevelService;
	@Resource
	private IMemberRecordService	memberRecordService;
	
	@Resource
	private IRuleSetService			ruleSetService;
	@Resource
	private IGrowthValRecordService	growthValRecordService;
	
	/**
	 * 根据ID查询会员账户 @Title: findById @author: wuyicheng @date: 2017年3月27日下午5:30:49 @param id @return @throws
	 */
	@Override
	public MemberAccount findById(Long id) {
		return memberAccountMapper.findById(id);
	}
	
	/**
	 * 分页查询会员账号信息 @Title: findList @author: wuyicheng @date: 2017年4月27日下午4:30:06 @param memberAccount @param page @return @return: List<MemberAccount> @throws
	 */
	@Override
	public List<MemberAccount> findListByPage(MemberAccount memberAccount, Pagination page) {
		return memberAccountMapper.findListByPage(memberAccount, page);
	}
	
	/**
	 * 新增会员账户信息 @Title: insert @author: wuyicheng @date: 2017年3月27日下午5:30:49 @param memberAccount @throws
	 */
	@Override
	public void insert(MemberAccount memberAccount) {
		memberAccount.setCreateTime(DateUtils.getCurrentDateTime());
		memberAccount.setUpdateTime(DateUtils.getCurrentDateTime());
		memberAccount.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		memberAccount.setRegisterTime(DateUtils.getCurrentDateTime());
		memberAccountMapper.insert(memberAccount);
	}
	
	/**
	 * @Title: update @author: wuyicheng @date: 2017年3月27日下午5:30:49 @param memberAccount @throws
	 */
	@Override
	public void update(MemberAccount memberAccount) {
		memberAccount.setUpdateTime(DateUtils.getCurrentDateTime());
		memberAccountMapper.update(memberAccount);
	}
	
	/**
	 * @Title: deleteById @author: wuyicheng @date: 2017年3月27日下午5:30:49 @param id @throws
	 */
	@Override
	public void delete(MemberAccount memberAccount) {
		memberAccount.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
		update(memberAccount);
	}
	
	/**
	 * @Title: findByMemberId @author: wuyicheng @date: 2017年3月30日下午3:31:21 @param memberId @return @throws
	 */
	@Override
	public MemberAccount findByMemberId(Long id) {
		// return memberAccountMapper.findByMemberId(memberId);
		return null;
	}
	
	/**
	 * @Title: findByMemberAccount @author: wuyicheng @date: 2017年3月31日下午3:33:22 @param memberAccount @return @return: MemberAccount @throws
	 */
	@Override
	public MemberAccount findByMemberAccount(MemberAccount memberAccount) {
		return memberAccountMapper.findMemberAccount(memberAccount);
	}
	
	/**
	 * @Title: findByMemberAccount @author: wuyicheng @date: 2017年3月31日下午3:33:22 @param memberAccount @return @return: MemberAccount @throws
	 */
	@Override
	public MemberAccount findByMemberAccountForUpdate(MemberAccount memberAccount) {
		return memberAccountMapper.findByMemberAccountForUpdate(memberAccount);
	}
	
	@Override
	public MemberAccountVo findByMemberAccount(Map<String, Object> map) {
		return memberAccountMapper.findByMemberAccount(map);
	}
	
	/**
	 * @return 新增会员信息 @Title: createMemberAccount @author: wuyicheng @date: 2017年4月20日下午8:24:04 @param loginName @param password @param referralCode @param sysId @throws
	 */
	@Override
	public MemberInfoVo createMemberAccount(String loginName, String password, String referralCode, Long sysId) {
		Member member = memberService.findByLoginName(loginName);
		if (member == null) {
			member = new Member();
			member.setMemberAccount(loginName);
			member.setReferralCode(null);
			member.setPhone(loginName);
			memberService.insert(member);
		}
		MemberAccount memberAccount = new MemberAccount();
		memberAccount.setPassword(password);
		memberAccount.setSysId(sysId);
		memberAccount.setMemberId(member.getId());
		memberAccount.setTotalAmount(new BigDecimal(0.00));
		memberAccount.setTotalIntegral(0);
		memberAccount.setTotalRefundAmount(new BigDecimal(0));
		memberAccount.setMemberLevelId(13L);
		memberAccount.setStatus(MemberStatus.ACTIVE);
		memberAccount.setCumulativeConsume(new BigDecimal(0));
		memberAccount.setCumulativeIntegral(0);
		insert(memberAccount);
		
		MemberInfoVo memberInfoVo = new MemberInfoVo();
		member = memberService.findById(member.getId());
		memberAccount = memberAccountMapper.findById(memberAccount.getId());
		memberInfoVo.setMember(member);
		memberInfoVo.setMemberAccount(memberAccount);
		return memberInfoVo;
	}
	
	/**
	 * 第三方登录创建会员信息 @Title: createMember @author: wuyicheng @date: 2017年4月20日下午8:30:39 @param thirdAccount @throws
	 */
	@Override
	public void createMember(ThirdAccount thirdAccount) {
		// 第三方登录创建信息
		Member member = new Member();
		MemberAccount memberAccount = new MemberAccount();
		member.setMemberAccount(null);
		member.setReferralCode(null);
		member.setPhone(null);
		memberService.insert(member);
		memberAccount.setPassword(null);
		memberAccount.setSysId(thirdAccount.getSysId());
		memberAccount.setMemberId(member.getId());
		memberAccount.setTotalAmount(new BigDecimal(0.00));
		memberAccount.setTotalIntegral(0);
		memberAccount.setTotalRefundAmount(new BigDecimal(0));
		memberAccount.setMemberLevelId(13L);
		memberAccount.setStatus(MemberStatus.ACTIVE);
		memberAccount.setCumulativeConsume(new BigDecimal(0));
		memberAccount.setCumulativeIntegral(0);
		insert(memberAccount);
		thirdAccount.setMemberId(member.getId());
	}
	
	/**
	 * @throws ParseException
	 * @throws CustomException
	 * @Title: doRegister @author: wuyicheng @date: 2017年4月24日下午7:05:17 @param loginName @param password @param sysId @param result @return @throws
	 */
	/*
	 * (non-Javadoc)
	 * @see com.zuipin.service.IMemberAccountService#doRegister(java.lang.String, java.lang.String, java.lang.Long, com.zuipin.framework.result.Result, java.lang.String)
	 */
	@Override
	public Result<MemberInfoVo> doRegister(String loginName, String password, Long sysId, Result<MemberInfoVo> result, String device) throws CustomException, ParseException {
		if (StringUtil.isBlank(loginName)) {
			result.setErrorCode(ErrorCode.NULL_POINT);
			result.setMessage("memberAccount is not null");
		} else if (StringUtil.isBlank(password)) {
			result.setErrorCode(ErrorCode.NULL_POINT);
			result.setMessage("password is not null");
		} else {
			boolean flag = doIsExist(loginName, sysId);
			if (!flag) {
				// 加密
				password = Encryption.createPassword(password);
				MemberInfoVo memberInfoVo = createMemberAccount(loginName, password, null, sysId);
				result.setErrorCode(ErrorCode.SUCCESS);
				ruleSetService.sendByUserBehavior(sysId, null, memberInfoVo.getMember().getId(), device, ShowType.REG.toString());
				result.setData(memberInfoVo);
			} else {
				result.setErrorCode(ErrorCode.OBJECT_EXIST);
				result.setMessage("member is exist");
			}
		}
		return result;
	}
	
	/**
	 * 账号是否存在 @Title: doIsExist @author: wuyicheng @date: 2017年4月24日下午7:20:41 @param loginName @param sysId @return @throws
	 */
	@Override
	public boolean doIsExist(String loginName, Long sysId) {
		Member member = memberService.findByLoginName(loginName);
		if (member != null) {
			MemberAccount memberAccount = findByMemberIdAndSysId(member.getId(), sysId);
			if (memberAccount != null) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 账号是否存在 @Title: doIsExist @author: wuyicheng @date: 2017年4月24日下午7:20:41 @param memberId 会员ID @param sysId 系统ID @return @throws
	 */
	@Override
	public boolean doIsExist(Long memberId, Long sysId) {
		Member member = memberService.findById(memberId);
		if (member != null) {
			MemberAccount memberAccount = findByMemberIdAndSysId(member.getId(), sysId);
			if (memberAccount != null) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 密码登录 @Title: doLoginByPwd @author: wuyicheng @date: 2017年4月24日下午8:39:20 @param memberAccount @param password @param sysId @param result @return @throws
	 * 
	 * @throws ParseException
	 * @throws CustomException
	 */
	@Override
	public Result<MemberInfoVo> doLoginByPwd(String memberAccount, String password, Long sysId, Result<MemberInfoVo> result, String device) throws CustomException, ParseException {
		MemberInfoVo memberInfoVo = new MemberInfoVo();
		Member member = memberService.findByLoginName(memberAccount);
		if (member != null) {
			MemberAccount userAccount = new MemberAccount();
			userAccount.setMemberId(member.getId());
			userAccount.setSysId(sysId);
			userAccount = findByMemberAccount(userAccount);
			if (userAccount != null) {
				if (filterMemberStatus(userAccount, result)) {
					return result;
				}
				boolean flag = pwdIsEquals(password, userAccount.getPassword());
				if (flag) {
					memberInfoVo.setMember(member);
					memberInfoVo.setMemberAccount(userAccount);
					result.setErrorCode(ErrorCode.SUCCESS);
					result.setData(memberInfoVo);
					ruleSetService.sendByUserBehavior(sysId, null, member.getId(), device, ShowType.LOGIN.toString());
					
				} else {
					result.setErrorCode(ErrorCode.PASSWORD_ERROR);
					result.setMessage("password is error");
					result.setData(null);
				}
			} else {
				result.setErrorCode(ErrorCode.NOT_FIND);
				result.setMessage("memberAccount is not exist");
				result.setData(null);
			}
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("member is not exist");
			result.setData(null);
		}
		return result;
	}
	
	/**
	 * 判断密码是否正确 @Title: pwdIsEquals @author: wuyicheng @date: 2017年4月24日下午8:44:11 @param password 新密码 @param userPwd 当前系统保存密码 @return @return: boolean @throws
	 */
	@Override
	public boolean pwdIsEquals(String password, String userPwd) {
		if (StringUtil.isNotBlank(userPwd)) {
			String[] str = userPwd.split(":");
			if (str != null && str.length >= 2) {
				String s1 = str[0];
				String s2 = str[1];// 随机码
				password = Encryption.md5(s2 + password);
				if (password.equals(s1)) {
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 短信登录 @Title: doLoginBySms @author: wuyicheng @date: 2017年4月24日下午8:53:52 @param loginName @param sysId @param result @return @throws
	 * 
	 * @throws ParseException
	 * @throws CustomException
	 */
	@Override
	public Result<MemberInfoVo> doLoginBySms(String loginName, Long sysId, Result<MemberInfoVo> result, String device) throws CustomException, ParseException {
		MemberInfoVo memberInfoVo = new MemberInfoVo();
		Member member = memberService.findByLoginName(loginName);
		if (member != null) {
			MemberAccount userAccount = new MemberAccount();
			userAccount.setMemberId(member.getId());
			userAccount.setSysId(sysId);
			userAccount = findByMemberAccount(userAccount);
			if (userAccount != null) {
				if (filterMemberStatus(userAccount, result)) {
					return result;
				}
				memberInfoVo.setMember(member);
				memberInfoVo.setMemberAccount(userAccount);
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setData(memberInfoVo);
				ruleSetService.sendByUserBehavior(sysId, null, member.getId(), device, ShowType.LOGIN.toString());
			} else {
				result.setErrorCode(ErrorCode.NOT_FIND);
				result.setMessage("memberAccount is not find");
				result.setData(null);
			}
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("member is not find");
			result.setData(null);
		}
		return result;
	}
	
	/**
	 * 第三方登录 @Title: doLoginByThirdLogin @author: wuyicheng @date: 2017年4月24日下午9:03:05 @param openId @param platformId 平台基础信息表ID @param nickName 第三方平台ID @param sysId 系统ID @param result @return @throws
	 * 
	 * @throws ParseException
	 * @throws CustomException
	 */
	@Override
	public Result<MemberInfoVo> doLoginByThirdLogin(String openId, Long platformId, String nickName, Long sysId, String unionId, Result<MemberInfoVo> result, String device)
			throws CustomException, ParseException {
		ThirdAccount thirdAccount = thirdAccountService.findByOpenId(openId, unionId, platformId, sysId);
		// 新建第三方账号
		if (thirdAccount == null) {
			thirdAccount = new ThirdAccount();
			thirdAccount.setOpenId(openId);
			thirdAccount.setSysId(sysId);
			thirdAccount.setPlatformId(platformId);
			thirdAccount.setNickName(nickName);
			thirdAccount.setUnionId(unionId);
			thirdAccountService.insert(thirdAccount);
		} else if (isModNickNaneAndUnionId(nickName, unionId, thirdAccount)) {
			// 如果昵称或者union修改了，更新
			thirdAccount.setNickName(nickName);
			thirdAccount.setUnionId(unionId);
			thirdAccountService.update(thirdAccount);
		}
		// 是否绑定会员
		if (thirdAccount.getMemberId() != null) {
			Member member = memberService.findById(thirdAccount.getMemberId());
			if (member != null) {
				MemberAccount userAccount = new MemberAccount();
				userAccount.setMemberId(member.getId());
				userAccount.setSysId(sysId);
				userAccount = findByMemberAccount(userAccount);
				if (userAccount != null) {
					if (filterMemberStatus(userAccount, result)) {
						return result;
					}
					MemberInfoVo memberInfoVo = new MemberInfoVo();
					memberInfoVo.setMember(member);
					memberInfoVo.setMemberAccount(userAccount);
					memberInfoVo.setThirdAccount(thirdAccount);
					result.setErrorCode(ErrorCode.SUCCESS);
					result.setData(memberInfoVo);
					ruleSetService.sendByUserBehavior(sysId, null, member.getId(), device, ShowType.LOGIN.toString());
					
				} else {
					result.setErrorCode(ErrorCode.NOT_FIND);
					result.setMessage("memberAccount is not find");
					result.setData(null);
				}
			} else {
				result.setErrorCode(ErrorCode.NOT_FIND);
				result.setMessage("member is not find");
				result.setData(null);
			}
			
		} else {
			MemberInfoVo memberInfoVo = new MemberInfoVo();
			memberInfoVo.setMember(null);
			memberInfoVo.setMemberAccount(null);
			memberInfoVo.setThirdAccount(thirdAccount);
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(memberInfoVo);
		}
		
		return result;
	}
	
	/**
	 * 判断用户名和union是否修改 @param unionId @param nickName @Title: isModNickNaneAndUnionId @author: wuyicheng @date: 2017年5月17日下午4:03:49 @param thirdAccount @return @return: boolean @throws
	 */
	private boolean isModNickNaneAndUnionId(String nickName, String unionId, ThirdAccount thirdAccount) {
		//
		if (StringUtil.isNotBlank(nickName) && !(nickName.equals(thirdAccount.getNickName()))) {
			return true;
		}
		//
		if (StringUtil.isNotBlank(unionId) && !(unionId.equals(thirdAccount.getUnionId()))) {
			return true;
		}
		return false;
	}
	
	/**
	 * 找回密码 @Title: findPwd @author: wuyicheng @date: 2017年4月24日下午9:31:05 @param loginName @param password @param sysId @param result @return @throws
	 */
	@Override
	public Result<Map<String, Object>> findPwd(String loginName, String password, Long sysId, Result<Map<String, Object>> result) {
		Member member = memberService.findByLoginName(loginName);
		if (member != null) {
			MemberAccount userAccount = new MemberAccount();
			userAccount.setMemberId(member.getId());
			userAccount.setSysId(sysId);
			userAccount = findByMemberAccount(userAccount);
			if (userAccount != null) {
				boolean isEquals = pwdIsEquals(password, userAccount.getPassword());
				if (isEquals) {
					result.setErrorCode(ErrorCode.OLD_IS_NOT_EQUALS_NEW);
					result.setMessage("new password is not equals old password");
				} else {
					MemberAccount tempMemberAccount = new MemberAccount();
					password = Encryption.createPassword(password);
					tempMemberAccount.setPassword(password);
					tempMemberAccount.setId(userAccount.getId());
					update(tempMemberAccount);
					result.setErrorCode(ErrorCode.SUCCESS);
				}
			} else {
				result.setErrorCode(ErrorCode.NOT_FIND);
			}
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
		}
		return result;
	}
	
	/**
	 * 修改密码 @Title: updatePwd @author: wuyicheng @date: 2017年4月24日下午9:37:29 @param memberId @param sysId @param password @param newPwd @param result @return @throws
	 */
	@Override
	public Result<Map<String, Object>> updatePwd(Long memberId, Long sysId, String password, String newPwd, Result<Map<String, Object>> result) {
		MemberAccount userAccount = new MemberAccount();
		Member member = memberService.findById(memberId);
		if (member != null) {
			if (StringUtil.isBlank(member.getPhone())) {
				result.setErrorCode(ErrorCode.DB_EXCEPTION);
				result.setMessage("account not binding mobile phone");
				result.setData(null);
			} else {
				userAccount.setMemberId(memberId);
				userAccount.setSysId(sysId);
				userAccount = findByMemberAccount(userAccount);
				if (userAccount != null) {
					if (StringUtil.isBlank(userAccount.getPassword())) {
						result.setErrorCode(ErrorCode.DB_EXCEPTION);
						result.setMessage("password is null");
						result.setData(null);
					} else if (password.equals(newPwd)) {
						result.setErrorCode(ErrorCode.OLD_IS_NOT_EQUALS_NEW);
						result.setMessage("new password is not equals old password");
						result.setData(null);
					} else {
						boolean flag = pwdIsEquals(password, userAccount.getPassword());
						if (flag) {
							newPwd = Encryption.createPassword(newPwd);
							MemberAccount tempMemberAccount = new MemberAccount();
							tempMemberAccount.setPassword(newPwd);
							tempMemberAccount.setId(userAccount.getId());
							update(tempMemberAccount);
							result.setErrorCode(ErrorCode.SUCCESS);
						} else {
							result.setErrorCode(ErrorCode.PASSWORD_ERROR);
							result.setMessage("memberAccount is error or password is error");
						}
						result.setData(null);
					}
				} else {
					result.setErrorCode(ErrorCode.NOT_FIND);
					result.setMessage("memberAccount is not exist");
					result.setData(null);
				}
			}
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("member is not exist");
			result.setData(null);
		}
		return result;
	}
	
	@Override
	public MemberAccount findByMemberIdAndSysId(Long memberId, Long sysId) {
		MemberAccount memberAccount = new MemberAccount();
		memberAccount.setMemberId(memberId);
		memberAccount.setSysId(sysId);
		return findByMemberAccount(memberAccount);
	}
	
	/**
	 * 判断会员是否绑定手机号 @Title: isBindingMobilePhone @author: wuyicheng @date: 2017年4月26日下午7:02:27 @param memberId @return @throws
	 */
	@Override
	public boolean isBindingMobilePhone(Long memberId) {
		if (memberId != null) {
			Member member = memberService.findById(memberId);
			if (member != null && StringUtil.isNotBlank(member.getPhone())) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public List<MemberAccount> findByMemberIdsAndSysId(List<Long> memberIds, Long sysId) {
		Map<String, Object> map = new HashMap<>();
		map.put("memberIds", memberIds);
		map.put("sysId", sysId);
		return memberAccountMapper.findListByMap(map);
	}
	
	@Override
	public Result<MemberAccount> findMemberByUnionId(String unionId, Long sysId, Long platformId, Result<MemberAccount> result) {
		ThirdAccount thirdAccount = new ThirdAccount();
		thirdAccount.setSysId(sysId);
		thirdAccount.setUnionId(unionId);
		thirdAccount.setPlatformId(platformId);
		ThirdAccount account = thirdAccountService.findByThirdAccount(thirdAccount);
		if (account != null) {
			MemberAccount memberAccount = new MemberAccount();
			memberAccount.setMemberId(account.getMemberId());
			memberAccount.setSysId(sysId);
			MemberAccount member = findByMemberAccount(memberAccount);
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(member);
		} else {
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(null);
		}
		return result;
	}
	
	/**
	 * 更新消费金额、成长值 @Title: updateConsumption @author: wuyicheng @date: 2017年6月20日下午2:56:36 @param memberId 会员ID @param sysId 系统ID @param totalAmount 订单应付总金额（包含充值余额） @param GrowthValue 成长值 @param isAdd
	 * 是否添加，true+ false- @param remark 备注 @throws CustomException @return: void @throws
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateConsumption(Long memberId, Long sysId, BigDecimal totalAmount, Integer growthValue, boolean isAdd, String remark, String describes, String oddNumbers,
			Long sysUserId, GrowthValType growthValType) throws CustomException {
		MemberAccount memberAccount = findByMemberIdAndSysId(memberId, sysId);
		if (memberAccount != null) {
			MemberLevel memberLevel = memberLevelService.findById(memberAccount.getMemberLevelId());
			if (memberLevel != null) {
				
				// 成长值记录表
				GrowthValRecord growthValRecrod = new GrowthValRecord();
				growthValRecrod.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
				growthValRecrod.setMemberId(memberId);
				growthValRecrod.setSysId(sysId);
				growthValRecrod.setCreateId(sysUserId);
				growthValRecrod.setDescribes(describes);
				growthValRecrod.setOddNumbers(oddNumbers);
				growthValRecrod.setUpdateId(sysUserId);
				growthValRecrod.setGrowthValType(growthValType);
				growthValRecrod.setRemark(remark);
				if (!isAdd) {
					totalAmount = ArithUtil.mul(totalAmount, new BigDecimal(-1.00));
					growthValue = growthValue * -1;
				}
				
				// 变更的成长值
				growthValRecrod.setAlterGrowthVal(growthValue);
				
				// 累计消费
				BigDecimal cumulativeConsume = ArithUtil.add(totalAmount, memberAccount.getCumulativeConsume(), 2);
				
				if (MemberLevel.Agent_LEVEL_V13.equals(memberLevel.getLever())) {
					
					// 代理商不赠送成长值，不升级
					
				} else {
					
					Integer currentGrowthValue = memberAccount.getGrowthValue() == null ? 0 : memberAccount.getGrowthValue();
					
					growthValRecrod.setBeforeGrowthVal(currentGrowthValue);
					
					// 累计成长值
					Integer totalGrowthValue = currentGrowthValue + growthValue;
					
					growthValRecrod.setAfterGrowthVal(totalGrowthValue);
					memberAccount.setGrowthValue(totalGrowthValue);
					
					MemberLevel nextLevel = null;
					// 积分超出1 000 000
					boolean ischangeLevel = false;
					if (MemberLevel.MAX_GROETH_VALUE <= totalGrowthValue) {
						if (MemberLevel.MAX_MEMBER_LEVEL != memberLevel.getId()) {
							memberAccount.setMemberLevelId(MemberLevel.MAX_MEMBER_LEVEL);
							ischangeLevel = true;
						}
					} else {
						nextLevel = memberLevelService.findByGrowthValue(sysId, totalGrowthValue);
						if (nextLevel != null) {
							if (nextLevel.getId() != memberLevel.getId().intValue()) {
								memberAccount.setMemberLevelId(nextLevel.getId());
								ischangeLevel = true;
							}
						} else {
							throw new CustomException(ErrorCode.MEMBER_LEVEL_IS_NULL.getCode(), "会员等级异常!成长值为=" + totalGrowthValue);
						}
					}
					// 级别变更添加日志
					if (ischangeLevel) {
						MemberRecord memberRecord = new MemberRecord();
						memberRecord.setLogType(MemberRecordType.UPGRADE);
						memberRecord.setMemberId(memberId);
						StringBuilder sb = new StringBuilder();
						
						// 确认收货送成长值(订单号：XXXXXXXX)
						sb.append(remark).append("(").append(describes).append(":").append(oddNumbers);
						memberRecord.setRemark(sb.toString() + ",由" + memberLevel.getLever() + "到" + nextLevel.getLever());
						memberRecord.setSysId(sysId);
						memberRecordService.insert(memberRecord);
						
					}
					
				}
				memberAccount.setCumulativeConsume(cumulativeConsume);
				memberAccountMapper.update(memberAccount);
				growthValRecordService.insert(growthValRecrod);
			} else {
				throw new CustomException(ErrorCode.MEMBER_LEVEL_IS_NULL.getCode(), "会员等级异常!");
			}
		} else {
			throw new CustomException(ErrorCode.MEMBER_ACCOUNT_NOT_EXIST.getCode(), "会员账号不存在!");
		}
	}
	
	/**
	 * @Title: getGrowthValue @author: wuyicheng @date: 2017年6月20日下午2:07:32 @param actualPayTotalAmount @param memberLevel @return @throws
	 */
	@Override
	public Integer getGrowthValue(BigDecimal actualPayTotalAmount, MemberLevel memberLevel) {
		BigDecimal consumGrowthRatio = memberLevel.getConsumGrowthRatio();
		Integer growthValue = ArithUtil.mul(consumGrowthRatio, actualPayTotalAmount, 2).intValue();
		return growthValue;
	}
	
	/**
	 * 查询会员信息
	 *
	 * @Title: searchSendMember 
	 * @author: wuyicheng
	 * @date: 2017年7月26日下午1:00:12 
	 * @param searchMap
	 * @return
	 * @throws
	 */
	@Override
	public List<Map<String, Object>> searchSendMember(Map<String, Object> searchMap) {
		return memberAccountMapper.searchMemberByMap(searchMap);
	}
	
	/** 
	 * @Title: updateIntegral 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param id
	 * @param @param num
	 * @throws 
	 */
	@Override
	public void updateIntegral(Long id, Integer num) {
		// TODO Auto-generated method stub
		memberAccountMapper.updateIntegral(id, num);
	}
	
	/** 
	 * @Title: updateIntegral 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param id
	 * @param @param num
	 * @throws 
	 */
	@Override
	public void updateAmount(Long id, BigDecimal num) {
		// TODO Auto-generated method stub
		memberAccountMapper.updateAmount(id, num);
	}
	
	/** 
	 * @Title: findByMemberIdAndSysIdForUpdate 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param memberId
	 * @param @param sysId
	 * @param @return
	 * @throws 
	 */
	@Override
	public MemberAccount findByMemberIdAndSysIdForUpdate(Long memberId, Long sysId) {
		MemberAccount memberAccount = new MemberAccount();
		memberAccount.setMemberId(memberId);
		memberAccount.setSysId(sysId);
		return findByMemberAccountForUpdate(memberAccount);
	}
	
	/**
	 * 过滤会员状态    不可用返回true 可用返回false
	  *  @Title: filterMemberStatus
	  * @author joy.zhang
	  * @date 2017年8月9日 下午2:18:20
	  * @param userAccount
	  * @param result
	  * @return
	  * @return boolean true 冻结  false 正常
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean filterMemberStatus(MemberAccount userAccount, Result result) {
		// 会员为空
		if (userAccount == null) {
			if (result != null) {
				result.setErrorCode(ErrorCode.NOT_FIND);
				result.setMessage("会员账号没有找到");
				result.setData(null);
			}
			return true;
		}
		// 会员状态判断
		if (userAccount.getStatus() != null && !MemberStatus.ACTIVE.equals(userAccount.getStatus())) {
			if (result != null) {
				result.setErrorCode(ErrorCode.MEMBER_IS_FREEZE);
				result.setMessage(ErrorCode.MEMBER_IS_FREEZE.getCnMessage());
				result.setData(null);
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 过滤会员状态   不可用返回true 可用返回false
	  *  @Title: filterMemberStatus
	  * @author joy.zhang
	  * @date 2017年8月9日 下午2:44:07
	  * @param memberId 会员Id
	  * @param sysId 系统Id
	  * @param result 错误信息
	  * @return
	  * @return boolean
	 */
	@SuppressWarnings("rawtypes")
	public boolean filterMemberStatus(Long memberId, Long sysId, Result result) {
		// 下单会员状态校验
		MemberAccount userAccount = new MemberAccount();
		userAccount.setMemberId(memberId);
		userAccount.setSysId(sysId);
		userAccount = findByMemberAccount(userAccount);
		return filterMemberStatus(userAccount, result);
	}
}